package com.pxl.springbootinit.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserDetailsService userDetailsService;

    public SecurityConfig(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/imgs/**").permitAll() // 允许访问 /imgs 下的所有资源
                .antMatchers("/user/login", "/user/register").permitAll()  // 允许公共访问的路径
                .antMatchers("/swagger-ui/**", "/v2/api-docs/**", "/doc.html", "/favicon.ico", "/swagger-resources/**", "/webjars/**", "/api-docs").permitAll()
                .antMatchers("/task/page","/items/rank/**").permitAll()
                .antMatchers("/api/chat/**").permitAll() // 允许 WebSocket 请求通过，不做认证
                .antMatchers("/**").permitAll()
                .antMatchers("/**/admin/**").hasRole("ADMIN")  // 只有管理员可以访问的路径
                .anyRequest().authenticated()  // 其他所有路径都需要认证
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();  // 使用 BCrypt 加密密码
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
